package com.hackordie.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/ajax")
public class AjaxController extends AMainController {
              
    @RequestMapping(value = "/shop/pages/{page}", method = RequestMethod.POST)
    public @ResponseBody AjaxComponents shopPagesAJAX(@PathVariable("page") int page) throws Exception {

        AjaxComponents listComponents = new AjaxComponents();
       
        int PAGE_FIELDS = 10;
        int pages = (int) Math.ceil((double) hodManager.countAllComponents() / (double) PAGE_FIELDS);
        int begin = Math.max(1, page - 5);
        int end = Math.min(begin + 10, pages);

        listComponents.setTotalPages(pages);
        listComponents.setBeginIndex(begin);
        listComponents.setEndIndex(end);
        listComponents.setCurrentIndex(page);        

        int first = (page - 1) * PAGE_FIELDS;
        int last = first + (PAGE_FIELDS);
                                      
        listComponents.setComponents(hodManager.getAllComponentsByRange(first, last));  
              
        return listComponents;
    }
    
    @RequestMapping(value = "/shop/buy/{userId}/{idComponent}", method = RequestMethod.POST)
    public @ResponseBody AjaxComponents shopBuyComponent(@PathVariable("userId") int userId, @PathVariable("idComponent") int idComponent) throws Exception {

        AjaxComponents listComponents = new AjaxComponents();
                     
        //TODO ver usuario por id, ver precio de componente, si tiene dinero 
        //update al dinero del usuario, agregar componente en la BD
        //seleccionar todos los componentes del usuario, devolverlos
        //pintar la pagina (con javascript)

        int componentId = idComponent;
              
        return listComponents;
    }
}
